/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkTcpClient.h"
#include "MkEvent/MkEvent.h"
#include "MkUtil/MkUtil.h"
#include "MkUtil/MkLog.h"


CMkTcpClient::CMkTcpClient(CMkEvent* pEvent, CMkTimer* pTimer, const MkEventRemovedCallback& RemovedCb)
    : CMkSocket(TcpClient, pEvent, pTimer)
    , m_RemovedCb(RemovedCb)
{

}

Uint32 CMkTcpClient::ConnectServer(const MkString& Ip, Uint16 Port, const MkConnectedCallback& ConnectCb)
{
    m_ConnectedCb = ConnectCb;
    if (IsConnected()
        && GetRemotePort() == Port
        && Ip == GetRemoteHost()) {
        //MkDebugLog("this:%p is connected\n", this);
        return OnConnect();
    }
    if (INVALID_SOCKET != Socket()) {
        Close();
    }
    Uint32 ErrorCode = Create();
    MkCheckErrorLog(ErrorCode, "create socket failed\n");
    return CMkSocket::Connect(Ip, Port);
}

void CMkTcpClient::DeleteLater()
{
    if (GetEvent()) {
        GetEvent()->AddPipTask([this]() {
            delete this;
        });
    } else {
        delete this;
    }
}

Uint32 CMkTcpClient::OnEventRemoved()
{
    if (m_RemovedCb) {
        m_RemovedCb(this);
    }
    return CMkSocket::OnEventRemoved();
}

Uint32 CMkTcpClient::OnConnect()
{
    CMkSocket::OnConnect();
    if (m_ConnectedCb) {
        m_ConnectedCb();
    }
    return NoneError;
}

CMkTcpClient::~CMkTcpClient()
{

}